//
// Initialization and Shutdown of CasablancaService1.dll.
//

#include "stdafx.h"
#include <http_listener.h>

using namespace http;
using namespace http::listener;

http_listener g_listener;

// Function to help find dynamically assigned port for our endpoint.
casablanca::string_t find_addr(const std::vector<casablanca::string_t> &configs)
{
    // The configuration data is a vector of [key1,value1,key2,value2,...,keyN,valueN] pairs.
    for(auto iter = configs.begin(); iter != configs.end(); ++iter)
    {
        if(*iter == U("EndPoint1"))
        {
            ++iter;
            return U("http://*:") + *iter;
        }
    }
    return U("http://*");
}

bool on_initialize(const std::vector<casablanca::string_t> &args, const std::vector<casablanca::string_t> &configs)
{
    // TODO: Implement on_initialize. This will be called by Casablanca when CasablancaService1.dll is loaded.
    // Often this will include things like creating an http_listener or hosting/spawning actors.
    // 'args' contains any command line arguments, which can only be specified when running locally not in Azure.
    // 'configs' contains any settings from actors_config.cfg and the port numbers for each Azure endpoint. 

    // As example here is a basic http_listener to get you going.
    g_listener = http_listener::create(find_addr(configs));

    // Associate request handlers with each of the four main HTTP request methods.

    // GET
    g_listener.support(methods::GET, [](http_request message)
    {
        message.reply(http::status_codes::OK, U("Hello World!"));
        actors::log::post(actors::LOG_INFO, U("Serviced a GET request for ") + message.request_uri().to_string());
    });

    // PUT
    g_listener.support(methods::PUT, [](http_request message)
    {
        message.reply(http::status_codes::OK, U("Hello World!"));
        actors::log::post(actors::LOG_INFO, U("Serviced a PUT request for ") + message.request_uri().to_string());
    });

    // POST
    g_listener.support(methods::POST, [](http_request message)
    {
        message.reply(http::status_codes::OK, U("Hello World!"));
        actors::log::post(actors::LOG_INFO, U("Serviced a POST request for ") + message.request_uri().to_string());
    });

    // DELETE
    g_listener.support(methods::DEL, [](http_request message)
    {
        message.reply(http::status_codes::OK, U("Hello World!"));
        actors::log::post(actors::LOG_INFO, U("Serviced a DEL request for ") + message.request_uri().to_string());
    });

    return g_listener.open() == 0;
}

bool on_shutdown()
{
    // TODO: Implement on_shutdown. This will be called by Casablanca when CasablancaService1.dll is unloaded.
    return g_listener.close() == 0;
}